package com.tjec.project.projectWorkbench.service.impl;

import com.tjec.common.enums.CodeNum;
import com.tjec.common.enums.NumCode;
import com.tjec.common.utils.DateUtils;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.ServletUtils;
import com.tjec.common.utils.StringUtils;
import com.tjec.framework.security.service.TokenService;
import com.tjec.framework.web.domain.server.Sys;
import com.tjec.project.businessWorkbench.domain.BmsBusiness;
import com.tjec.project.businessWorkbench.mapper.BmsBusinessDocArchiveMapper;
import com.tjec.project.businessWorkbench.mapper.BmsBusinessMapper;
import com.tjec.project.msg.service.MsgService;
import com.tjec.project.portal.service.IBmsMsgService;
import com.tjec.project.projectWorkbench.domain.BmsProject;
import com.tjec.project.projectWorkbench.domain.BmsProjectMember;
import com.tjec.project.projectWorkbench.domain.BmsProjectMemberHistory;
import com.tjec.project.projectWorkbench.mapper.BmsProjectMapper;
import com.tjec.project.projectWorkbench.mapper.BmsProjectMemberHistoryMapper;
import com.tjec.project.projectWorkbench.mapper.BmsProjectMemberMapper;
import com.tjec.project.projectWorkbench.service.IBmsProjectMemberHistoryService;
import com.tjec.project.projectWorkbench.service.IBmsProjectMemberService;
import com.tjec.project.projectWorkbench.service.IBmsProjectService;
import com.tjec.project.system.domain.SysUser;
import com.tjec.project.system.mapper.SysUserMapper;

import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * 项目成员Service业务层处理
 *
 * @author tjec
 * @date 2020-04-10
 */
@Service
public class BmsProjectMemberServiceImpl implements IBmsProjectMemberService {
    @Autowired
    private BmsProjectMemberMapper bmsProjectMemberMapper;

    @Autowired
    private IBmsProjectMemberHistoryService bmsProjectMemberHistoryService;

    @Autowired
    private IBmsProjectService bmsProjectService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private BmsProjectMapper bmsProjectMapper;

    @Autowired
    private IBmsMsgService bmsMsgService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private BmsBusinessMapper bmsBusinessMapper;

    @Autowired
    private MsgService msgService;

    @Autowired
    private BmsBusinessDocArchiveMapper bmsBusinessDocArchiveMapper;

    /**
     * 查询项目成员
     *
     * @param guid 项目成员guid
     * @return 项目成员
     */
    @Override
    public BmsProjectMember selectBmsProjectMemberByGuid(String guid) {
        return bmsProjectMemberMapper.selectBmsProjectMemberByGuid(guid);
    }

    /**
     * 查询项目成员列表
     *
     * @param bmsProjectMember 项目成员
     * @return 项目成员
     */
    @Override
    public List<BmsProjectMember> selectBmsProjectMemberList(BmsProjectMember bmsProjectMember) {
        return bmsProjectMemberMapper.selectBmsProjectMemberList(bmsProjectMember);
    }

    /**
     * 查询未包含的项目成员列表
     *
     * @param bmsProjectMember 项目成员
     * @param leader           项目负责人ID
     * @return 项目成员集合
     */
    @Override
    public List<BmsProjectMember> selectNotInBmsProjectMemberList(BmsProjectMember bmsProjectMember, String leader) {
        return bmsProjectMemberMapper.selectNotInBmsProjectMemberList(bmsProjectMember, leader);
    }

    /**
     * 新增项目成员
     *
     * @param bmsProjectMember 项目成员
     * @return 结果
     */
    @Transactional
    @Override
    public int insertBmsProjectMember(BmsProjectMember bmsProjectMember) {
        bmsProjectMember.setCreateTime(DateUtils.getNowDate());
        if(tokenService.getLoginUser(ServletUtils.getRequest()) != null) {
        	bmsProjectMember.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        }

        if (null == bmsProjectMember.getGuid() || ("").equals(bmsProjectMember.getGuid())) {
            bmsProjectMember.setGuid(UUID.randomUUID().toString());
        }
        updateProjectManger(bmsProjectMember);
        insertBmsProjectMemberHistoryByIns(bmsProjectMember);

        //新增项目成员发送系统消息
        //获取用户信息
        SysUser user = sysUserMapper.selectUserById(bmsProjectMember.getUserId());
        //根据项目id获取项目信息
        BmsProject project = bmsProjectMapper.selectBmsProjectByGuid(bmsProjectMember.getProjectId());

        String msgType = "新增项目成员";
        String content = "";
        if(tokenService.getLoginUser(ServletUtils.getRequest()) != null) {
        	 content = tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getNickName() + "：您已被加入"+project.getName()+"项目。";
        }else {
        	 content = "系统管理员：您已被加入"+project.getName()+"项目。";
        }

        if(tokenService.getLoginUser(ServletUtils.getRequest()) != null) {
        	//发送系统消息
            bmsMsgService.insertByReceiverUser(user.getUserId(), msgType, content,true);
        }

        //发送短信消息
        msgService.SendMsg2(user.getPhonenumber(), content);

        return bmsProjectMemberMapper.insertBmsProjectMember(bmsProjectMember);
    }

    /**
     * 添加项目成员变更记录(新增操作)
     * @param
     */
    public int insertBmsProjectMemberHistoryByIns(BmsProjectMember bmsProjectMember){
        BmsProjectMemberHistory projectMemberHistory = new BmsProjectMemberHistory();
        projectMemberHistory.setUserId(bmsProjectMember.getUserId());
        projectMemberHistory.setProjectId(bmsProjectMember.getProjectId());
        projectMemberHistory.setWorkContent(bmsProjectMember.getWorkContent());
        projectMemberHistory.setWorkload(bmsProjectMember.getWorkload());
        projectMemberHistory.setRemark("加入项目");
        projectMemberHistory.setRole(bmsProjectMember.getRole());
        return bmsProjectMemberHistoryService.insertBmsProjectMemberHistory(projectMemberHistory);
    }

    /**
     * 更新项目表的项目经理（如果删除状态为0，设置用户为项目经理，如果为2则设置项目经理为空）
     * @param bmsProjectMember
     * @return
     */
    public int updateProjectManger(BmsProjectMember bmsProjectMember){
        if(StringUtils.isNotBlank(bmsProjectMember.getProjectId())&&bmsProjectMember.getRole().equals("0")){
            BmsProject bmsProject = new BmsProject();
            bmsProject.setGuid(bmsProjectMember.getProjectId());
            if(bmsProjectMember.getDelFlag()!=null&&bmsProjectMember.getDelFlag().equals("2")){
                bmsProject.setProjectManager(null);
            }else{
                bmsProject.setProjectManager(bmsProjectMember.getUserId());
                //更新其他项目经理为项目成员,同时添加历史记录
                BmsProjectMember projectMember = new BmsProjectMember();
                projectMember.setProjectId(bmsProjectMember.getProjectId());
                List<BmsProjectMember> bmsProjectMembers = bmsProjectMemberMapper.selectBmsProjectMemberList(projectMember);
                for (BmsProjectMember member : bmsProjectMembers) {
                    member.setRole("1");
                    insertBmsProjectMemberHistoryByUpdate(member);
                }
                bmsProjectMemberMapper.updateBmsProjectMemberAsMember(bmsProjectMember.getProjectId());
            }
            return bmsProjectService.updateBmsProjectManager(bmsProjectMember.getProjectId(), bmsProject.getProjectManager());
        }else{
            return 0;
        }
    }

    /**
     * 修改项目成员
     *
     * @param bmsProjectMember 项目成员
     * @return 结果
     */
    @Transactional
    @Override
    public int updateBmsProjectMember(BmsProjectMember bmsProjectMember) {
        bmsProjectMember.setUpdateTime(DateUtils.getNowDate());
        bmsProjectMember.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        insertBmsProjectMemberHistoryByUpdate(bmsProjectMember);
        updateProjectManger(bmsProjectMember);
        //原项目角色为项目经理，修改为项目成员，同步修改项目表项目经理为null
        BmsProjectMember oldBmsProjectMember = bmsProjectMemberMapper.selectBmsProjectMemberByGuid(bmsProjectMember.getGuid());
        if(oldBmsProjectMember.getRole().equals("0")&&bmsProjectMember.getRole().equals("1")){
            bmsProjectService.updateBmsProjectManager(bmsProjectMember.getProjectId(), null);
        }
        return bmsProjectMemberMapper.updateBmsProjectMember(bmsProjectMember);
    }

    /**
     * 添加项目成员变更记录(修改操作)
     * @param bmsProjectMember
     */
    public int insertBmsProjectMemberHistoryByUpdate(BmsProjectMember bmsProjectMember){
        String remaks = "";
        if(StringUtils.isBlank(bmsProjectMember.getGuid())){
            return 0;
        }
        BmsProjectMember oldBmsProjectMember = selectBmsProjectMemberByGuid(bmsProjectMember.getGuid());
        if(StringUtils.isNoneBlank(oldBmsProjectMember.getRole(), bmsProjectMember.getRole())&&!oldBmsProjectMember.getRole().equals(bmsProjectMember.getRole())){
            remaks +="修改项目角色";
            BmsProjectMemberHistory projectMemberHistory = new BmsProjectMemberHistory();
            projectMemberHistory.setUserId(bmsProjectMember.getUserId());
            projectMemberHistory.setProjectId(bmsProjectMember.getProjectId());
            projectMemberHistory.setRemark(remaks);
//        projectMemberHistory.setWorkContent(oldBmsProjectMember.getWorkContent());
//        projectMemberHistory.setWorkload(oldBmsProjectMember.getWorkload());
            projectMemberHistory.setRole(bmsProjectMember.getRole());
            return bmsProjectMemberHistoryService.insertBmsProjectMemberHistory(projectMemberHistory);
        }
        /*if(StringUtils.isNoneBlank(oldBmsProjectMember.getWorkContent(), bmsProjectMember.getWorkContent())&&!oldBmsProjectMember.getWorkContent().equals(bmsProjectMember.getWorkContent())){
            remaks +="修改工作内容; ";
        }
        if(null!=oldBmsProjectMember.getWorkload()&&null!=bmsProjectMember.getWorkload()&&!oldBmsProjectMember.getWorkload().equals(bmsProjectMember.getWorkload())){
            remaks +="修改工作量;";
        }
        if(StringUtils.isNoneBlank(oldBmsProjectMember.getRemark(), bmsProjectMember.getRemark())&&!oldBmsProjectMember.getRemark().equals(bmsProjectMember.getRemark())){
            remaks +="修改备注;";
        }*/
        return 0;
    }

    /**
     * 添加项目成员变更记录(删除操作)
     * @param guid
     */
    public int insertBmsProjectMemberHistoryByDel(String guid){
        if(StringUtils.isBlank(guid)){
            return 0;
        }
        BmsProjectMember oldBmsProjectMember = selectBmsProjectMemberByGuid(guid);
        BmsProjectMemberHistory projectMemberHistory = new BmsProjectMemberHistory();
        projectMemberHistory.setUserId(oldBmsProjectMember.getUserId());
        projectMemberHistory.setProjectId(oldBmsProjectMember.getProjectId());
        projectMemberHistory.setWorkContent(oldBmsProjectMember.getWorkContent());
        projectMemberHistory.setWorkload(oldBmsProjectMember.getWorkload());
        projectMemberHistory.setRemark("移除项目");
        projectMemberHistory.setRole(oldBmsProjectMember.getRole());
        return bmsProjectMemberHistoryService.insertBmsProjectMemberHistory(projectMemberHistory);
    }

    /**
     * 批量删除项目成员
     *
     * @param guids 需要删除的项目成员guid
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBmsProjectMemberByGuids(String[] guids, String type)throws Exception{
        int j = 0;
        if (null != guids && guids.length > 0) {
            for (int i = 0; i < guids.length; i++) {
                deleteBmsProjectMemberByGuid(guids[i], type);
                j++;
            }
        }
        return j;
    }

    /**
     * 清除该招标组组长或组员
     * @param guid
     */
    private void removeTenderTeam(String guid, List<BmsBusiness> bmsBusinesses) {
        if(CollectionUtils.isEmpty(bmsBusinesses)||StringUtils.isBlank(guid)){
            return;
        }
        BmsProjectMember bmsProjectMember = bmsProjectMemberMapper.selectBmsProjectMemberByGuid(guid);
        for (BmsBusiness bmsBusiness : bmsBusinesses) {
            if(bmsProjectMember.getUserId().equals(bmsBusiness.getTenderLeader())){
                bmsBusiness.setTenderLeader("");
            }
            if(StringUtils.isNotBlank(bmsBusiness.getTenderMember())){
                bmsBusiness.setTenderMember(bmsBusiness.getTenderMember().replace(bmsProjectMember.getUserId()+";",""));
            }
            bmsBusinessMapper.updateBmsBusiness(bmsBusiness);
        }
    }

    /**
     * 删除项目成员信息
     *
     * @param guid 项目成员guid
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteBmsProjectMemberByGuid(String guid, String type) throws Exception{
        if (StringUtils.isBlank(guid)||StringUtils.isBlank(type)) {
            return 0;
        }
        BmsProjectMember projectMember = bmsProjectMemberMapper.selectBmsProjectMemberByGuid(guid);
        //根据项目id获取项目信息
        BmsProject project = bmsProjectMapper.selectBmsProjectByGuid(projectMember.getProjectId());
        List<BmsBusiness> bmsBusinesses = bmsBusinessMapper.selectBmsBusinessByProjectId(projectMember.getProjectId());

        //删除成员
        BmsProjectMember bmsProjectMember = bmsProjectMemberMapper.selectBmsProjectMemberByGuid(guid);
        if(bmsProjectMember.getRole().equals("0")&&type.equals("prjectGeneral")){
            throw new Exception("项目经理不能移除");
        }
        //如果移除为项目经理，同步修改项目表上的项目负责人
        if(bmsProjectMember.getRole().equals("0")&&!type.equals("prjectList")){
            bmsProjectService.updateBmsProjectManager(bmsProjectMember.getProjectId(),"");
        }
        insertBmsProjectMemberHistoryByDel(guid);
        //判断移除项目成员是否存在为招标组长或组员，如果存在，则清除该招标组组长或组员
        removeTenderTeam(guid, bmsBusinesses);

        bmsProjectMember.setGuid(guid);
        //删除标志
        bmsProjectMember.setDelFlag("2");
        updateBmsProjectMember(bmsProjectMember);

        String msgType = "移除项目成员";
        String content = tokenService.getLoginUser(ServletUtils.getRequest()).getUser().getNickName() + "：您已被从"+project.getName()+"项目中移除。";
        bmsMsgService.insertByReceiverUser(bmsProjectMember.getUserId(), msgType, content,true);
        return bmsProjectMemberMapper.deleteBmsProjectMemberByGuid(guid);
    }

    @Override
    public int selectBmsProjectMemberByUserId(String userId) {
        return bmsProjectMemberMapper.selectBmsProjectMemberByUserId(userId);
    }

    @Override
    public Set<String> selectBmsProjectMemberByUserIdOrProjectStatus(BmsProjectMember bmsProjectMember) {
        return bmsProjectMemberMapper.selectBmsProjectMemberByUserIdOrProjectStatus(bmsProjectMember);
    }

    /**
     * 查询历史项目信息变更
     *
     * @param bmsProjectMember
     * @return
     */
    @Override
    public List<BmsProjectMember> selectHistoryProjectList(BmsProjectMember bmsProjectMember) {
        return bmsProjectMemberMapper.selectHistoryProjectList(bmsProjectMember);
    }

    /**
     * 统计项目人数
     *
     * @param bmsProjectMember
     * @return
     */
    @Override
    public Integer countBmsProjectMemberNo(BmsProjectMember bmsProjectMember) {
        return bmsProjectMemberMapper.countBmsProjectMemberNo(bmsProjectMember);
    }

    /**
     * 在项目中项目组员并且不是招标组长/成员为true,否则为false
     * @param userId
     * @param projectId
     * @return
     */
   /* @Override
    public boolean isTenderMember(String userId,String projectId) {
        boolean flag = false;
        if(StringUtils.isBlank(userId)||StringUtils.isBlank(projectId)){
            flag = false;
        }

        //先判断当前登陆人是否是项目负责人或项目经理
        String res = bmsBusinessDocArchiveMapper.checkUserByProjectId(userId, projectId);
        if("1".equals(res)) {
        	return false;
        }

        BmsProjectMember bmsProjectMember = new BmsProjectMember();
        bmsProjectMember.setProjectId(projectId);
        bmsProjectMember.setUserId(userId);
        List<String> result = bmsProjectMemberMapper.isTenderMember(bmsProjectMember);
        //该用户是否在项目成员中为项目成员角色
        bmsProjectMember.setRole("1");
        List<BmsProjectMember> bmsProjectMembers = bmsProjectMemberMapper.selectBmsProjectMemberList(bmsProjectMember);
        if(!CollectionUtils.isEmpty(bmsProjectMembers)&&CollectionUtils.isEmpty(result)){
            flag = true;
        }
        return flag;
    }*/


    /**
     * 在项目中项目组员并且不是招标组长/成员为true,否则为false
     * @param userId
     * @param bmsBusiness
     * @return
     */
    @Override
    public boolean isTenderMembers(String userId, BmsBusiness bmsBusiness) {
        boolean flag = true;
        if(bmsBusiness!=null&&StringUtils.isNotBlank(userId)){
            //先判断当前登陆人是否是项目负责人或项目经理
            String res = bmsBusinessDocArchiveMapper.checkUser(userId, bmsBusiness.getGuid());
            if("1".equals(res)) {
                return false;
            }
            //该用户是为招标组员或组长
            if(StringUtils.isNotBlank(bmsBusiness.getTenderLeader())&&bmsBusiness.getTenderLeader().contains(userId)){
                return false;
            }
            if(StringUtils.isNotBlank(bmsBusiness.getTenderMember())&&bmsBusiness.getTenderMember().contains(userId)){
                return false;
            }
        }
        return flag;
    }

    /**
     *查询项目负责人所属项目下的项目成员中是否存在该用户
     * @param leader 项目负责人ID
     * @param userGuid
     * @return
     */
    @Override
    public List<BmsProjectMember> selectBmsProjectMemberListByLeaderAndUserGuids(String leader, String[] userGuid) {
        return bmsProjectMemberMapper.selectBmsProjectMemberListByLeaderAndUserGuids(leader, userGuid);
    }

    /**
     * 是否重复添加项目成员
     * @param projectId
     * @param userId
     * @return
     */
    @Override
    public boolean repeatBmsProjectMember(String projectId, String userId) {
        //查询是否重复添加项目成员
        BmsProjectMember repeatBmsProjectMember = new BmsProjectMember();
        repeatBmsProjectMember.setProjectId(projectId);
        repeatBmsProjectMember.setUserId(userId);
        repeatBmsProjectMember.setDelFlag("0");
        List<BmsProjectMember> list = this.selectBmsProjectMemberList(repeatBmsProjectMember);
        if(!CollectionUtils.isEmpty(list)){
            return true;
        }
        return false;
    }

    /**
     * 查询负责人人员并且不在项目成员中
     * @param bmsProjectMember
     * @return
     */
    @Override
    public List<BmsProjectMember> selectBmsProjectMemberNoProjectMember(BmsProjectMember bmsProjectMember) {
        return bmsProjectMemberMapper.selectBmsProjectMemberNoProjectMember(bmsProjectMember);
    }
}
